﻿using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;
using ServiceClient;
using WebMvc.Dao;

namespace WebMvc
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        // Provider that holds the application container.
        private static IContainerProvider containerProvider;

        /// <summary>
        /// Instance property that will be used by Autofac HttpModules
        /// to resolve and inject dependencies.
        /// </summary>
        /// <value>
        /// The container provider.
        /// </value>
        public IContainerProvider ContainerProvider
        {
            get { return containerProvider; }
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            // Build up your application container and register your dependencies.
            var builder = new ContainerBuilder();

            /*** Registro los tipos ***/

            // IDbConnection
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            builder.RegisterInstance(conn).As<IDbConnection>();

            builder.RegisterType<TicketDao>().AsSelf();
            builder.RegisterType<SalaDao>().AsSelf();
            builder.RegisterType<OpenMeetingsServiceClient>().AsSelf().SingleInstance();

            // ... continue registering dependencies and register your controllers...
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            // .. and you can register model binders
            // builder.RegisterModelBinders(Assembly.GetExecutingAssembly());

            // Once you're done registering things, set the container
            // provider up with your registrations.
            containerProvider = new ContainerProvider(builder.Build());

            // Set the controller factory using the container provider.
            ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider));

            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }
    }
}